package com.cy.pj.eiems.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cy.pj.eiems.Exception.ServiceException;
import com.cy.pj.eiems.dao.EiemsLogDao;
import com.cy.pj.eiems.entity.EiemsLog;
import com.cy.pj.eiems.service.EiemsLogService;
import com.cy.pj.eiems.vo.PageObject;


@Service
@Transactional
public class EiemsLogServiceImpl implements EiemsLogService {
	@Autowired
	private EiemsLogDao eiemsLogDao;

	@Override
	public PageObject<EiemsLog> findPageObjects(String username, Integer pageCurrent) {
		// 1.对参数进行校验
		if (pageCurrent == null || pageCurrent < 1)
			throw new IllegalArgumentException("当前页码值无效");
		// 2.查询总记录数并进行校验
		int rowCount = eiemsLogDao.getRowCount(username);
		if (rowCount == 0)
			throw new ServiceException("没有找到对应记录");
		// 3.查询当前页记录
		int pageSize = 4;
		int startIndex = (pageCurrent - 1) * pageSize;
		List<EiemsLog> records = eiemsLogDao.findPageObjects(username, startIndex, pageSize);
		// 4.对查询结果进行封装并返回
		return new PageObject<>(pageCurrent, pageSize, rowCount, records);
	}

	@Override
	public int deleteObjects(Integer... ids) {
		// 1.判定参数合法性
		if (ids == null || ids.length == 0)
			throw new IllegalArgumentException("请选择一个");
		// 2.执行删除操作
		int rows;
		try {
			rows = eiemsLogDao.deleteObjects(ids);
		} catch (Throwable e) {
			e.printStackTrace();
			// 发出报警信息(例如给运维人员发短信)
			throw new ServiceException("系统故障，正在恢复中...");
		}
		// 4.对结果进行验证
		if (rows == 0)
			throw new ServiceException("记录可能已经不存在");
		// 5.返回结果
		return rows;

	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	@Async // 表示使用异步方式写日志
	@Override
	public void saveObject(EiemsLog entity) {
		String tName = Thread.currentThread().getName();
		System.out.println("log.save.thread.name " + tName);
		eiemsLogDao.insertObject(entity);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
		}
	}

}
